package com.corpgovernment.job.batchimport.util;

import com.corpgovernment.job.batchimport.entity.FillErrorEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author ldma
 * @date 2024/1/17
 */
@Component
public class BatchImportExcelUtils {

    public void fillError(XSSFWorkbook workbook, List<FillErrorEntity> fillErrorEntityList) {
        // 单元格样式设置
        CellStyle style = workbook.createCellStyle();
        XSSFFont font = workbook.createFont();
        font.setColor(IndexedColors.RED.getIndex());
        style.setFont(font);
        style.setDataFormat(workbook.createDataFormat().getFormat("@"));
        style.setFillForegroundColor(IndexedColors.GOLD.getIndex());
        style.setFillBackgroundColor(IndexedColors.GOLD.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 只针对第一个sheet
        XSSFSheet sheet = workbook.getSheetAt(0);
        for (FillErrorEntity  item: fillErrorEntityList) {
            // 直接获取到第几行进行错误填充
            fillErrorRow(sheet.getRow(item.getRow()), item.getCol(), style, item.getErrorMsg());
        }
    }

    private void fillErrorRow(Row row, int cellIndex, CellStyle cellStyle, String errorMsg) {
        for (int i = 0; i <= cellIndex; i++) {
            Cell cell = row.getCell(i);
            if (cell == null) {
                cell = row.createCell(i);
            }
            if (i == cellIndex) {
                fillErrorCell(cell, cellStyle, errorMsg);
            }
            fillErrorCell(cell, cellStyle, null);
        }
    }

    private void fillErrorCell(Cell cell, CellStyle cellStyle, String errorMsg) {
        if (StringUtils.isNotBlank(errorMsg)) {
            cell.setCellValue(errorMsg);
        }
        cell.setCellStyle(cellStyle);
    }

}
